package com.yugao.fintech.libra.shortlink.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.libra.common.BasePlusPO;
import com.yugao.fintech.libra.common.util.SecurityUtils;
import com.yugao.fintech.libra.shortlink.assembly.DomainAssembly;
import com.yugao.fintech.libra.shortlink.manager.SlLinkDomainManager;
import com.yugao.fintech.libra.shortlink.mapper.SlLinkDomainMapper;
import com.yugao.fintech.libra.shortlink.mapper.SlShortLinkManager;
import com.yugao.fintech.libra.shortlink.model.entity.LinkDomain;
import com.yugao.fintech.libra.shortlink.model.entity.ShortLink;
import com.yugao.fintech.libra.shortlink.model.rqrs.DomainListReq;
import com.yugao.fintech.libra.shortlink.model.rqrs.DomainReq;
import com.yugao.fintech.libra.shortlink.service.DomainService;
import com.yugao.fintech.meheco.core.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DomainServiceImpl extends ServiceImpl<SlLinkDomainMapper, LinkDomain> implements DomainService {
    @Autowired
    private DomainAssembly domainAssembly;
    @Autowired
    private SlShortLinkManager linkGroupManagerManager;

    public DomainServiceImpl(SlLinkDomainManager domainManager) {
    }

    @Override
    public List<LinkDomain> listDomain(DomainListReq rq) {
        LambdaQueryWrapper<LinkDomain> lqw = LinkDomain.lqw()
                .like(StrUtil.isNotEmpty(rq.getDomain()), LinkDomain::getDomain, rq.getDomain())
                .orderByDesc(BasePlusPO::getCreatedAt);
        return this.list(lqw);
    }

    @Override
    public boolean saveDomain(DomainReq rq) {
        LinkDomain linkDomain = domainAssembly.toLinkDomain(rq);
        linkDomain.setUserId(SecurityUtils.getUserId());

        if (this.count(LinkDomain.lqw().eq(LinkDomain::getDomain, rq.getDomain())) > 0) {
            throw new BusinessException("域名已存在");
        }
        return this.save(linkDomain);
    }

    @Override
    public boolean updateDomain(DomainReq rq) {
        LinkDomain linkDomain = domainAssembly.toLinkDomain(rq);
        linkDomain.setUserId(SecurityUtils.getUserId());
        LambdaQueryWrapper<LinkDomain> lqw = LinkDomain.lqw().eq(LinkDomain::getDomain, rq.getDomain())
                .ne(LinkDomain::getId, rq.getId());
        if (this.count(lqw) > 0) {
            throw new BusinessException("域名已存在");
        }
        return this.updateById(linkDomain);
    }

    @Override
    public boolean deleteDomainByIds(List<Long> ids) {
        if (linkGroupManagerManager.count(ShortLink.lqw().eq(ShortLink::getDomainId, ids)) > 0) {
            throw new BusinessException("已有短链引用当前域名");
        }
        return this.removeByIds(ids);
    }
}
